<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发票管理系统 - 发票查询</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }

        .sidebar {
            height: 100vh;
            background-color: #343a40;
            color: white;
            position: fixed;
            width: 250px;
            padding-top: 20px;
        }

            .sidebar .nav-link {
                color: rgba(255, 255, 255, 0.8);
                margin-bottom: 5px;
                border-radius: 5px;
                padding: 10px 15px;
            }

                .sidebar .nav-link:hover {
                    background-color: #495057;
                    color: white;
                }

                .sidebar .nav-link.active {
                    background-color: #007bff;
                    color: white;
                }

        .main-content {
            margin-left: 250px;
            padding: 20px;
        }

        .search-card {
            margin-bottom: 20px;
        }

        .invoice-image-preview {
            max-width: 100%;
            max-height: 500px;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="text-center mb-4">
            <h4>发票管理系统</h4>
        </div>
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="welcome.html">
                    <i class="bi bi-house-door me-2"></i>首页
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="upload.html">
                    <i class="bi bi-upload me-2"></i>发票上传
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="query.html">
                    <i class="bi bi-search me-2"></i>发票查询
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="statistic.html">
                    <i class="bi bi-bar-chart me-2"></i>发票统计
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" id="logoutBtn">
                    <i class="bi bi-box-arrow-right me-2"></i>退出登录
                </a>
            </li>
        </ul>
    </div>

    <div class="main-content">
        <div class="container-fluid">
            <div class="row mb-4">
                <div class="col">
                    <h2>发票查询</h2>
                    <p class="text-muted">按日期范围或关键字查询发票信息</p>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="card search-card">
                        <div class="card-body">
                            <form id="searchForm">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="mb-3">
                                            <label for="startDate" class="form-label">开始日期</label>
                                            <input type="date" class="form-control" id="startDate">
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="mb-3">
                                            <label for="endDate" class="form-label">结束日期</label>
                                            <input type="date" class="form-control" id="endDate">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label for="keyword" class="form-label">关键字搜索</label>
                                            <input type="text" class="form-control" id="keyword" placeholder="输入发票号码、公司名称等">
                                        </div>
                                    </div>
                                    <div class="col-md-2 d-flex align-items-end">
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="bi bi-search me-2"></i>查询
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="invoiceTable" class="table table-striped table-hover" style="width:100%">
                                    <thead>
                                        <tr>
                                            <th>发票号码</th>
                                            <th>开票日期</th>
                                            <th>销售方</th>
                                            <th>购买方</th>
                                            <th>金额</th>
                                            <th>合计金额</th>
                                            <th>类型</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- 数据将通过JavaScript动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 发票图片查看模态框 -->
    <div class="modal fade" id="invoiceImageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="invoiceImageModalLabel">发票查看</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <img id="invoiceImagePreview" class="invoice-image-preview img-fluid" alt="发票图片">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script>
        // 检查用户是否已登录
        const user_id = localStorage.getItem('user_id');
        if (!user_id) {
            window.location.href = 'index.html';
        }

        document.getElementById('logoutBtn').addEventListener('click', function () {
            localStorage.removeItem('user_id');
            window.location.href = 'index.html';
        });

        // 初始化DataTable
        const invoiceTable = $('#invoiceTable').DataTable({
            columns: [
                { data: 'invoice_number' },
                { data: 'invoice_date' },
                { data: 'seller_name' },
                { data: 'buyer_name' },
                { data: 'amount' },
                { data: 'total_amount' },
                { data: 'invoice_type' },
                {
                    data: null,
                    render: function (data, type, row) {
                        return `<button class="btn btn-sm btn-outline-primary view-btn" data-image="${row.image_path}">查看</button>`;
                    },
                    orderable: false
                }
            ],
            language: {
                url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/zh.json'
            }
        });

        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', function (e) {
            e.preventDefault();
            searchInvoices();
        });

        // 查询发票
        function searchInvoices() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            const keyword = document.getElementById('keyword').value;

            let url = `http://127.0.0.1:8080/api/query?user_id=${user_id}`;

            if (startDate && endDate) {
                url += `&start_date=${startDate}&end_date=${endDate}`;
            }

            if (keyword) {
                url += `&keyword=${encodeURIComponent(keyword)}`;
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                    } else {
                        invoiceTable.clear();

                        data.invoices.forEach(invoice => {
                            invoiceTable.row.add({
                                invoice_number: invoice.invoice_number || '-',
                                invoice_date: invoice.invoice_date || '-',
                                seller_name: invoice.seller_name || '-',
                                buyer_name: invoice.buyer_name || '-',
                                amount: invoice.amount ? parseFloat(invoice.amount).toFixed(2) : '0.00',
                                total_amount: invoice.total_amount ? parseFloat(invoice.total_amount).toFixed(2) : '0.00',
                                invoice_type: invoice.invoice_type || '-',
                                image_path: invoice.image_path
                            });
                        });

                        invoiceTable.draw();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('查询失败，请稍后再试');
                });
        }

        // 查看发票图片
        $(document).on('click', '.view-btn', function () {
            const imagePath = $(this).data('image');
            const modal = new bootstrap.Modal(document.getElementById('invoiceImageModal'));

            document.getElementById('invoiceImagePreview').src = `http://127.0.0.1:8080/uploads/${imagePath}`;
            modal.show();
        });

        // 页面加载时默认查询最近30天的发票
        window.addEventListener('load', function () {
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(endDate.getDate() - 30);

            document.getElementById('startDate').valueAsDate = startDate;
            document.getElementById('endDate').valueAsDate = endDate;

            searchInvoices();
        });
    </script>
</body>
</html>